const WXAPI =""// require('apifm-wxapi')
Page({
	data: {
		orderId: 1,
		amount: 999.00,
		uploaderList: [],
    uploaderNum:0,
    showUpload:true,
    img:"",
		refundApplyDetail: undefined,

		type: null,
		typeItems: [
			'我要退款(无需退货)',
			'我要退货退款',
			'我要换货',
		],

		logisticsStatus: null,
		logisticsStatusItems: [
			'未收到货',
			'已收到货'
		],
		reasons: [
			"不喜欢/不想要",
			"空包裹",
			"未按约定时间发货",
			"快递/物流一直未送达",
			"货物破损已拒签",
			"退运费",
			"规格尺寸与商品页面描述不符",
			"功能/效果不符",
			"质量问题",
			"少件/漏发",
			"包装/商品破损",
			"发票问题",
		],
		showDialog: false,
		showtype:"",
		groups: [
			
			
		
				{ text: '我要退款(无需退货)', value: 0 },
				{ text:'我要退货退款', value: 1 },
				{ text: 	'我要换货', value: 2 }
		],
		reasonIndex: null,

		files: [],
		pics: [],
		maxImgCount: 9, //允许上传图片数,最多9张
	},
	onLoad: function(e) {
		this.setData({
			orderId: e.id,
			amount: e.amount
		});
	},
	onShow() {
		const _this = this
    const db = wx.cloud.database()
    const b = db.collection('orders').where({
      //_openid: wx.getStorageSync('openid'),
       _id:_this.data.orderId
    }).get({
      success:function(res) {
        console.log(res)
			if (res.data.length >0) {
				
			  if(res.data[0].logisticsStatus && res.data[0].logisticsStatus==1){
					_this.setData({
						groups: [
							{ text:'我要退货退款', value: 1 },
							{ text: 	'我要换货', value: 2 }
						],
					})
				}
				
				_this.setData({
					refundApplyDetail: res.data[0],
					logisticsStatus:res.data[0].logisticsStatus,
					
				 
					})
					//如果已经是退款状态 显示退款信息
					if(res.data[0].refundStatus){
						_this.setData({
						type: res.data[0].refundtype,
						reasonIndex:  res.data[0].reasonIndex,
						uploaderList:res.data[0].refundpic?res.data[0].refundpic:[],
					  uploaderNum:res.data[0].refundpic?res.data[0].refundpic.length:0,
						refundremark:res.data[0].refundremark
					})
					}
					//回显服务类型的text
					for (let index = 0; index < _this.data.groups.length; index++) {
						const element = _this.data.groups[index];
						if(element.value==res.data[0].refundtype){
							_this.setData({
								showtype:element.text
							})
						}
						
					}
      }
    }
		})
	},
	refundApplyCancel(e) {
		const _this = this
		const orderId = e.currentTarget.dataset.id;
   
    
    wx.showModal({
      title: '确定要取消退款退货吗？',
      content: '',
      success: function (res) {
        if (res.confirm) {
          const db = wx.cloud.database()
        
          db.collection('orders').doc(orderId).update({
            data:{
							 status:0,
							 refundStatus:null
						},
            success: function(res) {
              console.log(res)
              wx.navigateTo({
								url: "/pages/order/index"
							})
            }
          })
         
          
         
        }
      }
    })
	
	},
	typeChange(e) {
		this.setData({
			type: e.detail.value
		})
	},
	logisticsStatusChange(e) {
		
		this.setData({
			logisticsStatus: e.detail.value
		})
	},
	typeItemsChange: function(e) {
		
		const typeItems = this.data.typeItems;
		for (var i = 0, len = typeItems.length; i < len; ++i) {
			typeItems[i].checked = typeItems[i].value == e.detail.value;
		}
		this.setData({
			typeItems: typeItems,
			type: e.detail.value
		});
	},
	openDialog: function () {
		this.setData({
				showDialog: true
		})
},
closeDialog: function () {
		this.setData({
				showDialog: false
		})
},
btnClick(e) {
	
	var that =this
		console.log(e)
		that.setData({
			type: e.detail.value,//服务类型
			
		})
		//回显服务类型的text
		for (let index = 0; index < that.data.groups.length; index++) {
			const element = that.data.groups[index];
			if(element.value==e.detail.value){
				that.setData({
				 showtype:element.text
			 })
			}
			
		}
		this.closeDialog()
},
/*	logisticsStatusItemsChange: function(e) {
		const logisticsStatusItems = this.data.logisticsStatusItems;
		for (var i = 0, len = logisticsStatusItems.length; i < len; ++i) {
			logisticsStatusItems[i].checked = logisticsStatusItems[i].value == e.detail.value;
		}
		this.setData({
			logisticsStatusItems: logisticsStatusItems,
			logisticsStatus: e.detail.value
		});
	},*/
	reasonChange: function(e) {
		
		this.setData({
			reasonIndex: e.detail.value
		})
	},
	chooseImage: function(e) {
		const that = this;
		wx.chooseImage({
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			count: that.data.maxImgCount - that.data.files.length,
			success: function(res) {
				// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
				that.setData({
					files: that.data.files.concat(res.tempFilePaths)
				});
			}
		})
	},
	previewImage: function(e) {
		const that = this;
		wx.previewImage({
			current: e.currentTarget.id, // 当前显示图片的http链接
			urls: that.data.files // 需要预览的图片http链接列表
		})
	},
	delImg(e) {
		wx.showModal({
			title: '删除图片',
			content: '确定要删除这张图片吗？',
			cancelText: '取消',
			confirmText: '删除',
			success: res => {
				if (res.confirm) {
					this.data.files.splice(e.currentTarget.dataset.index, 1);
					this.setData({
						files: this.data.files
					})
				}
			}
		})
	},
	
//上传图片
upload: function(e) {
	var that = this;
	wx.chooseImage({
			count: 9 - that.data.uploaderNum, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: chooseResult => {
					console.log(chooseResult)
					wx.cloud.uploadFile({
							// 指定上传到的云路径
							cloudPath: (new Date()).valueOf()+'.png', // 文件名
							// 指定要上传的文件的小程序临时文件路径
							filePath: chooseResult.tempFilePaths[0],
							// 成功回调
							success: res => {
								console.log('上传成功', res)
								// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
								let tempFilePaths = res.fileID;
							 
								wx.cloud.getTempFileURL({
									fileList:[{
											fileID:tempFilePaths,
											maxAge:60*60


									}]
								}).then((res)=>{
									console.log(res.fileList)
									console.log(that.data.img )
									let uploaderList = that.data.uploaderList.concat(res.fileList[0].tempFileURL);
									console.log(uploaderList.length)
									if (uploaderList.length==9){
										that.setData({
												showUpload:false
										})
									}
									that.setData({
										uploaderList: uploaderList,
										uploaderNum: uploaderList.length,
									})
								})
								that.setData({
									 
								})
							},
						})
					
			}
	})
},
	 uploadPics() {
		const _this = this;
		for (let i = 0; i < _this.data.files.length; i++) {
			
			wx.cloud.uploadFile({
				// 指定上传到的云路径
				cloudPath: (new Date()).valueOf()+'.png', // 文件名
				// 指定要上传的文件的小程序临时文件路径
				filePath: _this.data.files[i],
				// 成功回调
				success: res => {
					console.log('上传成功', res)
					// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
					let tempFilePaths = res.fileID;
				 
					wx.cloud.getTempFileURL({
						fileList:[{
								fileID:tempFilePaths,
								maxAge:60*60
	
	
						}]
					}).then((res)=>{
						console.log(res.fileList)
						console.log(that.data.img )
						let uploaderList = that.data.uploaderList.concat(res.fileList[0].tempFileURL);
						console.log(uploaderList.length)
						if (uploaderList.length==9){
							that.setData({
									showUpload:false
							})
						}
						that.setData({
							uploaderList: uploaderList,
							uploaderNum: uploaderList.length,
						})
					})
					
				},
			})
		//	const res = await WXAPI.uploadFile(wx.getStorageSync('token'), _this.data.files[i])
		//	if (res.code == 0) {
		//		_this.data.pics.push(res.data.url)
		//	}
		}
	},
	clearImg:function(e){
    var nowList = [];//新数据
    var uploaderList = this.data.uploaderList;//原数据
    
    for (let i = 0; i < uploaderList.length;i++){
        if (i == e.currentTarget.dataset.index){
            continue;
        }else{
            nowList.push(uploaderList[i])
        }
    }
    this.setData({
        uploaderNum: this.data.uploaderNum - 1,
        uploaderList: nowList,
        showUpload: true
    })
},

//展示图片
showImg:function(e){
	var that=this;
	wx.previewImage({
			urls: that.data.uploaderList,
			current: that.data.uploaderList[e.currentTarget.dataset.index]
	})
},
	 bindSave(e) {
    
		// 提交保存
		const _this = this;
		
		if(_this.data.type==null){
			wx.showModal({
        title: '提示',
        content: '请选择服务类型',
      })
			return
		} if(_this.data.logisticsStatus==null){
			wx.showModal({
        title: '提示',
        content: '请选择货物状态',
      })
			return
		}
		 if(_this.data.reasonIndex==null){
			wx.showModal({
        title: '提示',
        content: '请选择售后原因',
      })
			return
		}
		let amount = e.detail.value.amount;
		if (_this.data.type == 2) {
			amount = 0.00
    }
    
		let remark = e.detail.value.refundremark;
		if (!remark) {
			remark = ''
		}
	
    const db = wx.cloud.database()
    db.collection('orders').doc(_this.data.orderId).update({
      data: {
				refundtype: _this.data.type,
				//refundtypeStr: _this.data.typeItems[_this.data.type],
				logisticsStatus: _this.data.logisticsStatus,
				reason: _this.data.reasons[_this.data.reasonIndex],
				reasonIndex:_this.data.reasonIndex,
			  refundamount: parseInt(amount),
				refundremark:remark,
				refundpic: _this.data.uploaderList,
				status:99,
				refundStatus:0//0提交 1 同意 2待收回 3打款 4拒绝
      },
      success: function(res) {
				console.log(res)
				wx.showModal({
          title: '成功',
          content: '提交成功，请耐心等待我们处理！',
          showCancel: false,
          confirmText: '我知道了',
          success(res) {
            wx.navigateBack({
							delta: 1,
						})
          }
        })
        
      }
    })
  
    return

		WXAPI.refundApply({
			token: wx.getStorageSync('token'),
			orderId: _this.data.orderId,
			type: _this.data.type,
			logisticsStatus: _this.data.logisticsStatus,
			reason: _this.data.reasons[_this.data.reasonIndex],
			amount,
			remark,
			pic: _this.data.pics.join()
		}).then(res => {
			if (res.code == 0) {
				wx.showModal({
					title: '成功',
					content: '提交成功，请耐心等待我们处理！',
					showCancel: false,
					confirmText: '我知道了',
					success(res) {
						wx.navigateTo({
							url: "/pages/order-list/index"
						})
					}
				})
			} else {
				wx.showModal({
					title: '失败',
					content: res.msg,
					showCancel: false,
					confirmText: '我知道了',
					success(res) {
						wx.navigateTo({
							url: "/pages/order-list/index"
						})
					}
				})
			}
		})
	}
});
